package com.sunrise.xdoc.interceptor;

import java.io.Serializable;
import java.util.Date;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.springframework.security.core.context.SecurityContextHolder;

import com.sunrise.xdoc.entity.AbstractAuditEntity;

/**
 * The Class AuditInterceptor.
 * 
 * @author Nguyen Duc Dung
 * @since 5/25/13 3:33 PM
 */
public class AuditInterceptor extends EmptyInterceptor {
	private static final long serialVersionUID = -4913344403879491190L;

	@Override
	public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		return updateEntity(entity, currentState, propertyNames);
	}

	@Override
	public boolean onSave(Object entity, Serializable id, Object[] currentState, String[] propertyNames, Type[] types) {
		return updateEntity(entity, currentState, propertyNames);
	}

	private boolean updateEntity(Object entity, Object[] currentState, String[] propertyNames) {
		if (entity instanceof AbstractAuditEntity) {
			for (int i = 0; i < propertyNames.length; i++) {
				switch (propertyNames[i]) {
				case "creationDateTime":
					if (currentState[i] == null) {
						currentState[i] = new Date();
					}
					break;
				case "modificationDateTime":
					currentState[i] = new Date();
					break;
				case "creationUser":
					if (((AbstractAuditEntity) entity).getId() == null) {
						currentState[i] = SecurityContextHolder.getContext().getAuthentication().getName();
					}
					break;
				case "modificationUser":
					currentState[i] = SecurityContextHolder.getContext().getAuthentication().getName();
					break;
				}
			}
			return true;
		}
		return false;
	}

}
